﻿using System.Collections.Generic;
using System;
using UnityEngine.SocialPlatforms;

class DataChangeBroadcast : Singleton<DataChangeBroadcast>
{
    public delegate void OnDataChanged(DataChangeType type, params object[] objs);

    private Dictionary<DataChangeType, System.Delegate> messageEventTable = new Dictionary<DataChangeType, System.Delegate>();
    private Dictionary<DataChangeType, int> messageEventCount = new Dictionary<DataChangeType, int>();

    public void Subscribe(DataChangeType type, OnDataChanged handler)
    {
        if (!messageEventTable.ContainsKey(type))
        {
            messageEventTable[type] = null;
        }
        messageEventTable[type] = (OnDataChanged)messageEventTable[type] + handler;
    }

    public void Unsubscribe(DataChangeType type, OnDataChanged handler)
    {
        if (!messageEventTable.ContainsKey(type))
        {
            messageEventTable[type] = null;
        }
        messageEventTable[type] = (OnDataChanged)messageEventTable[type] - handler;
    }

    public void RaiseEvent(DataChangeType type, params object[] objs)
    {
        if (messageEventTable.ContainsKey(type))
        {
            OnDataChanged handler = (OnDataChanged)messageEventTable[type];
            if (handler != null)
            {
                if (messageEventCount.ContainsKey(type) == false)
                {
                    messageEventCount.Add(type, 0);
                }
                messageEventCount[type] += 1;

                handler(type, objs);
            }
        }
    }

    public string GetDebugInfo()
    {
        string info = "";
        foreach (KeyValuePair<DataChangeType, int> pair in messageEventCount)
        {
            info += pair.Key + " : " + pair.Value + "\r\n";
        }
        return info;
    }
}

